using Microsoft.Practices.Unity;
using UnityDemo.InstanceManagerCode.LifeTimeModels;
using UnityDemo.Models;

namespace UnityDemo.InstanceManagerCode.LifetimeTypes
{
    internal class HierarchicalLifetimeManagerDemo : ISample
    {
        //For this lifetime manager, as for the ContainerControlledLifetimeManager, Unity returns
        //the same instance of the registered type or object each time you call the Resolve or ResolveAll
        //method or when the dependency mechanism injects instances into other classes. The distinction is
        //that when there are child containers, each child resolves its own instance of the object and does not
        //share one with the parent. When resolving in the parent, the behavior is like a container controlled
        //lifetime; when resolving the parent and the child you have different instances with each acting as a
        //container-controlled lifetime. If you have multiple children, each will resolve its own instance.
        public HierarchicalLifetimeManagerDemo()
        {
            var container = new UnityContainer();
            container.RegisterType<HierarchicalLifetimeInstance>(new HierarchicalLifetimeManager());

            UnityContainer parentContainer = container;
            var instance1 = parentContainer.Resolve<HierarchicalLifetimeInstance>();
            instance1.PrintHashCode();

            IUnityContainer childContiner = parentContainer.CreateChildContainer();

            var instance2 = childContiner.Resolve<HierarchicalLifetimeInstance>();
            instance2.PrintHashCode();
        }
    }
}